%%%-------------------------------------------------------------------
%%% @author Rain
%%% @copyright (C) 2022, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 31. 3月 2022 20:40
%%%-------------------------------------------------------------------
-module(ets_util).
-author("Rain").

%% API
-export([foldl/3]).


%% @doc 遍历ets表支持中断
foldl(F, Accu, T) ->
    ets:safe_fixtable(T, true),
    First = ets:first(T),
    try
        do_foldl(F, Accu, First, T)
    after
        ets:safe_fixtable(T, false)
    end.

do_foldl(_F, {break, Accu0}, _Key, _T) ->
    Accu0;
do_foldl(F, Accu0, Key, T) ->
    case Key of
        '$end_of_table' ->
            Accu0;
        _ ->
            do_foldl(F,
                lists:foldl(F, Accu0, ets:lookup(T, Key)),
                ets:next(T, Key), T)
    end.
